package io.wit.modules.wit.service.impl;

import cloud.dwz.entity.DeptUserEntity;
import io.wit.config.ConfigFile;
import io.wit.modules.dwz.DeptUserDao;
import io.wit.modules.sys.dao.SysUserDao;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.shiro.ShiroUtils;
import io.wit.modules.wit.dao.EmployeeDao;
import io.wit.modules.wit.entity.EmployeeEntity;
import io.wit.modules.wit.service.EmployeeService;
import io.wit.tool.ToolClient;
import io.wit.tool.ToolString;
import io.wit.tool.UploadFile;
import io.wit.tool.UploadObject;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
	private EmployeeDao employeeDao;

    @Autowired
	private DeptUserDao deptUserDao;

    @Value("${upload_dir_window}")
    private String dir_window;

    @Value("${upload_dir_linux}")
    private String dir_linux;

    @Value("${employee_dafualt_password}")
    private String dafualtPassword;

    @Autowired
    private SysUserDao sysUserDao;
	
	@Override
	public EmployeeEntity queryObject(Long dataId){
		return employeeDao.queryObject(dataId);
	}
	
	@Override
	public List<EmployeeEntity> queryList(Map<String, Object> map){
		return employeeDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return employeeDao.queryTotal(map);
	}
	
	@Override
	public Long save(final EmployeeEntity employee){
		employee.setCreateTime(new Date());
		employeeDao.save(employee);
        return employee.getDataId();
	}
	
	@Override
	public void update(final EmployeeEntity employee){
		employeeDao.update(employee);
	}
	
	@Override
	public void delete(Long dataId){
		employeeDao.delete(dataId);
	}
	
	@Override
    @Transactional
	public void deleteBatch(final Long[] dataIds){
        final List<Long> longs = employeeDao.getUserIds(dataIds);
        employeeDao.delEmployees(longs);//删除 tb_employee
        employeeDao.delDeptUsers(dataIds);//删除 tb_dept_user
		employeeDao.delUsers(dataIds);//删除用户表 sys_user
	}

	@Override
	public List<EmployeeEntity> getUserList(final Long subjectId) {
		return employeeDao.getUserList(subjectId);
	}

    @Override
    public String getTypeEducation(){
        final List<Map<String,Object>> list = employeeDao.getTypeEducation();
        return ToolClient.queryJson(list);
    }

    @Override
    public String queryMap(final Long dataId){
        return ToolClient.queryJson(employeeDao.queryMap(dataId));
    }

    @Override
    @Transactional
    public String saveEmployee(final HttpServletRequest request){
        final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
        final SysUserEntity loginUser = ShiroUtils.getUserEntity();
        final SysUserEntity user = new SysUserEntity();
        final DeptUserEntity deptUserEntity = new DeptUserEntity();
        final String username = loginUser.getUsername();
        final HashMap<String,String> formParams = ToolClient.getFormParams(request);
        formParams.remove("userId");
        if(username.equals(ConfigFile.KEY_SUPER)){
            final String user_name = formParams.get("user_name");
            if(user_name == null){
                return ToolClient.createJsonFail("请输入经营主体的登录账号");
            }
            final HashMap<String,Object> userInfo = sysUserDao.getUserInfo(user_name);
            if(userInfo == null){
                return ToolClient.createJsonFail(user_name+"主体登录账号不存在");
            }
            final int status = (Integer)userInfo.get("status");
            if(status == 0){
                return ToolClient.createJsonFail(user_name+"账号已被禁用");
            }
            final HashMap<String,Object> subjects = sysUserDao.getSubjectInfo(user_name);
            formParams.put("subject_id",String.valueOf(subjects.get("data_id")));//id
            formParams.put("subject_name",String.valueOf(subjects.get("name")));//名称
            deptUserEntity.setSubjectId((Long) subjects.get("data_id"));
        }else{
            final Long subjectId = loginUser.getSubjectId();
            final String subjectName = loginUser.getSubjectName();
            if(subjectId == null){
                return ToolClient.createJsonFail("你还未创建经营主体");
            }
            formParams.put("subject_id",String.valueOf(subjectId));//id
            formParams.put("subject_name",subjectName);//名称
            loginUser.setSubjectId(subjectId);
            deptUserEntity.setSubjectId(subjectId);
        }
        final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/photos",1,false);
        final String errorMsg = uploadObject.getErrorMsg();
        if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
        final String validates = ToolClient.validateField(formParams,"name","deptId","sex","ispoor","type","mobile","education_id","wagestype","isassociator");
        if(validates != null) return validates;
        final String isassociator = formParams.get("isassociator");
        formParams.put("employee_role_id",isassociator);
        final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
        if(listFiles != null){
            final StringBuilder sb = new StringBuilder();
            for(int i = 0; i < listFiles.size(); i++){
                final String uri = listFiles.get(i).getUrlFile();
                if(sb.toString().length() > 0){
                    sb.append(",").append(uri);
                }else{
                    sb.append(uri);
                }
            }
            formParams.put("pic",sb.toString());
        }
        final HashMap<String,Object> params = new HashMap<>();
        params.putAll(formParams);
        //保存员工表,用户表,部门人员
        final int rows = employeeDao.saveEmployee(params);
        final BigInteger userId = (BigInteger)params.get("data_id");
        final Long dataId =  userId.longValue();//员工id
        user.setEmployeeId(dataId);
        final String mobile = formParams.get("mobile");
        user.setUsername(mobile);//员工登录账号默认是手机号,默认密码为6个000000
        user.setMobile(mobile);
        user.setType(2);
        user.setStatus(1);
        //sha256加密
        final String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        user.setPassword(dafualtPassword);
        user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
        sysUserDao.save(user);//用户
        deptUserEntity.setUserId(user.getUserId());
        deptUserEntity.setDeptId(Long.parseLong(formParams.get("deptId")));
        deptUserDao.save(deptUserEntity);//部门用户
        return ToolClient.executeRows(rows);
    }

    @Override
    @Transactional
    public String editEmployee(final HttpServletRequest request){
        final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
        final SysUserEntity loginUser = ShiroUtils.getUserEntity();
        final SysUserEntity user = new SysUserEntity();
        final DeptUserEntity deptUserEntity = new DeptUserEntity();
        final String username = loginUser.getUsername();
        final HashMap<String,String> formParams = ToolClient.getFormParams(request);
        if(username.equals(ConfigFile.KEY_SUPER)){
            final String user_name = formParams.get("user_name");
            if(user_name == null){
                return ToolClient.createJsonFail("请输入经营主体的登录账号");
            }
            final HashMap<String,Object> userInfo = sysUserDao.getUserInfo(user_name);
            if(userInfo == null){
                return ToolClient.createJsonFail(user_name+"主体登录账号不存在");
            }
            final int status = (Integer)userInfo.get("status");
            if(status == 0){
                return ToolClient.createJsonFail(user_name+"账号已被禁用");
            }
            final HashMap<String,Object> subjects = sysUserDao.getSubjectInfo(user_name);
            formParams.put("subject_name",String.valueOf(subjects.get("name")));//名称
        }else{
            final Long subjectId = loginUser.getSubjectId();
            final String subjectName = loginUser.getSubjectName();
            if(subjectId == null){
                return ToolClient.createJsonFail("你还未创建经营主体");
            }
            formParams.put("subject_name",subjectName);//名称
        }
        final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/photos",1,false);
        final String errorMsg = uploadObject.getErrorMsg();
        if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
        final String validates = ToolClient.validateField(formParams,"name","deptId","userId","sex","ispoor","type","mobile","education_id","wagestype","isassociator");
        if(validates != null) return validates;
        final String isassociator = formParams.get("isassociator");
        final long userId = Long.parseLong(formParams.get("userId"));
        formParams.put("employee_role_id",isassociator);
        final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
        if(listFiles != null){
            final StringBuilder sb = new StringBuilder();
            for(int i = 0; i < listFiles.size(); i++){
                final String uri = listFiles.get(i).getUrlFile();
                if(sb.toString().length() > 0){
                    sb.append(",").append(uri);
                }else{
                    sb.append(uri);
                }
            }
            formParams.put("pic",sb.toString());
        }
        //保存员工表,用户表,部门人员
        final int rows = employeeDao.editEmployee(formParams);
        user.setMobile(formParams.get("mobile"));
        user.setUserId(userId);
        sysUserDao.update(user);//用户
        deptUserEntity.setDeptId(Long.parseLong(formParams.get("deptId")));
        deptUserEntity.setUserId(userId);
        deptUserDao.update(deptUserEntity);//部门用户
        return ToolClient.executeRows(rows);
    }
}